package com.bjpowernode;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author LittleDesire
 * @description
 * @date 2022-03-02 周三 15:25
 * @since 17
 */
public class 模拟事务 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bj","root","123");
            //1, 开启事务
            conn.setAutoCommit(false);
            // 4号 给3号 转账      3号+ 1000 = 2000
            ps = conn.prepareStatement("update t_user set sal=? where id = ?");
            ps.setInt(1,2000);
            ps.setInt(2,3);
            ps.executeUpdate();
            // 模拟 出现异常
            System.out.println(1/0);
            // 4号 - 1000 = 0
            ps = conn.prepareStatement("update t_user set sal=? where id = ?");
            ps.setInt(1,0);
            ps.setInt(2,4);
            ps.executeUpdate();
            // 提交事务
            conn.commit();
        } catch (Exception e) {
            // 回滚
            if (conn != null){
                try {
                    conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
